<template>
	<view class="report-container">
		<view class="header">
			<text class="title">生成系统报告</text>
		</view>

		<view class="form">
			<view class="form-item">
				<text class="label">开始时间</text>
				<picker mode="date" @change="onStartTimeChange">
					<view class="picker">{{ formattedStartTime || '请选择开始时间' }}</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="label">结束时间</text>
				<picker mode="date" @change="onEndTimeChange">
					<view class="picker">{{ formattedEndTime || '请选择结束时间' }}</view>
				</picker>
			</view>

			<view class="form-item">
				<text class="label">工单类型</text>
				<picker mode="selector" range-key="typeName" :range="typeOptions" @change="onTypeChange">
					<view class="picker">{{ selectedTypeText ? '已选类型：' + selectedTypeText : '请选择类型' }}</view>
				</picker>
			</view>

			<view class="button-group">
				<button class="submit-button" @click="generateReport">生成报表</button>
				<button class="export-button" @click="exportReport">导出报表</button>
			</view>
		</view>

		<view v-if="reportData" class="section">
			<view class="section-title">报表概况</view>
			<view class="report-result">
				<view class="report-item" v-for="(value, key) in reportData.stats" :key="key">
					<text class="report-label">{{ labelMap[key] }}</text>
					<text class="report-value">{{ formatPercentage(value, key) }}</text>
				</view>
			</view>
		</view>

		<view v-if="reportData && reportData.timeoutOrders.length" class="section">
			<view class="section-title">超时工单表</view>
			<view class="timeout-orders">
				<view class="order-card" v-for="(order, index) in reportData.timeoutOrders" :key="index">
					<view class="card-header">
						<text class="card-title">{{ order.title }}</text>
						<text class="card-status">{{ order.statusText }}</text>
					</view>
					<view class="card-content">
						<view class="card-row">
							<text class="card-label">工单编号：</text>{{ order.orderId }}
						</view>
						<view class="card-row">
							<text class="card-label">申请人ID：</text>{{ order.applicantId }}
						</view>
						<view class="card-row">
							<text class="card-label">创建时间：</text>{{ order.createTime }}
						</view>
						<view class="card-row">
							<text class="card-label">更新时间：</text>{{ order.updateTime }}
						</view>
						<view class="card-row">
							<text class="card-label">紧急程度：</text>
							<text class="urgency-badge" :class="{
									'urgency-high': order.urgency === 1,
									'urgency-medium': order.urgency === 2,
									'urgency-low': order.urgency === 3
								}">
								{{ formatUrgency(order.urgency) }}
							</text>
						</view>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				startTime: '',
				endTime: '',
				selectedTypeText: '',
				typeOptions: [],
				reportData: null,
				formattedStartTime: '',
				formattedEndTime: '',
				selectedWorkOrderTypeId: 0,
				labelMap: {
					totalCount: '总工单数',
					completedCount: '已完成工单数',
					completionRate: '完成率',
					pendingCount: '未完成工单数',
					timeoutCount: '超时工单数',
					timeoutRate: '超时率'
				}
			};
		},
		methods: {
			async fetchWorkOrderTypes() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: 'http://localhost:8082/api/applicant/TypeList',
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						}
					});
					if (res.statusCode === 200) {
						this.typeOptions = res.data.data;
					}
				} catch (err) {
					uni.showToast({
						title: '获取工单类型失败',
						icon: 'none'
					});
				}
			},
			formatUrgency(urgency) {
				switch (urgency) {
					case 1:
						return '低';
					case 2:
						return '中';
					case 3:
						return '高';
					default:
						return '未知';
				}
			},
			formatPercentage(value, key) {
				if (key === 'completionRate' || key === 'timeoutRate') {
					return `${parseFloat(value ).toFixed(2)}%`;
				}
				return value;
			},
			onStartTimeChange(e) {
				this.startTime = e.detail.value;
				this.formattedStartTime = this.formatDate(this.startTime);
			},
			onEndTimeChange(e) {
				this.endTime = e.detail.value;
				this.formattedEndTime = this.formatDate(this.endTime);
			},
			onTypeChange(e) {
				const selected = this.typeOptions[e.detail.value];
				this.selectedTypeText = selected.typeName;
				this.selectedWorkOrderTypeId = parseInt(selected.typeId, 10);
			},
			async generateReport() {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: 'http://localhost:8082/admin/reports',
						method: 'GET',
						header: {
							'Authorization': 'Bearer ' + token
						},
						data: {
							startTime: this.formatToRequiredDateTime(this.startTime),
							endTime: this.formatToRequiredDateTime(this.endTime),
							workOrderType: this.selectedWorkOrderTypeId
						}
					});
					if (res.statusCode === 200) {
						this.reportData = res.data.data;
						uni.showToast({
							title: '报表生成成功',
							icon: 'success'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				}
			},
			async exportReport() {
				if (!this.startTime || !this.endTime || !this.selectedWorkOrderTypeId) {
					uni.showToast({
						title: '请完整选择时间和类型',
						icon: 'none'
					});
					return;
				}
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.downloadFile({
						url: 'http://localhost:8082/admin/reports/export',
						header: {
							'Authorization': 'Bearer ' + token
						},
						method: 'GET',
						data: {
							startTime: this.formatToRequiredDateTime(this.startTime),
							endTime: this.formatToRequiredDateTime(this.endTime),
							workOrderType: this.selectedWorkOrderTypeId
						},
						success: (res) => {
							if (res.statusCode === 200) {
								uni.openDocument({
									filePath: res.tempFilePath,
									success: () => uni.showToast({
										title: '打开报表成功',
										icon: 'success'
									})
								});
							}
						}
					});
				} catch (err) {
					uni.showToast({
						title: '导出失败',
						icon: 'none'
					});
				}
			},
			formatDate(dateTime) {
				if (!dateTime) return '';
				const date = new Date(dateTime);
				return `${date.getFullYear()}-${(date.getMonth() + 1)
					.toString()
					.padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
			},
			formatToRequiredDateTime(dateTime) {
				if (!dateTime) return '';
				const date = new Date(dateTime);
				return `${date.getFullYear()}-${(date.getMonth() + 1)
					.toString()
					.padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}T00:00:00`;
			}
		},
		mounted() {
			this.fetchWorkOrderTypes();
		}
	};
</script>

<style scoped>
	.report-container {
		padding: 20rpx;
		background-color: #eef4ff;
	}

	.header {
		background: linear-gradient(to right, #3b82f6, #2563eb);
		color: white;
		padding: 30rpx;
		text-align: center;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(59, 130, 246, 0.5);
		margin-bottom: 24rpx;
	}

	.title {
		font-size: 38rpx;
		font-weight: bold;
	}

	.form {
		background: white;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
		margin-bottom: 32rpx;
	}

	.form-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 24rpx;
	}

	.label {
		font-size: 28rpx;
		color: #475569;
		margin-bottom: 8rpx;
	}

	.picker {
		padding: 20rpx;
		border: 1px solid #cbd5e1;
		border-radius: 12rpx;
		background-color: #f8fafc;
		font-size: 28rpx;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		gap: 20rpx;
		margin-top: 20rpx;
	}

	.submit-button,
	.export-button {
		flex: 1;
		padding: 20rpx;
		border-radius: 12rpx;
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
	}

	.submit-button {
		background-color: #2563eb;
		color: white;
	}

	.export-button {
		background-color: #60a5fa;
		color: white;
	}

	.section {
		margin-bottom: 40rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #1e3a8a;
		margin-bottom: 16rpx;
		border-left: 8rpx solid #3b82f6;
		padding-left: 12rpx;
	}

	.report-result {
		background: white;
		border-radius: 20rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.report-item {
		display: flex;
		justify-content: space-between;
		padding: 12rpx 0;
		border-bottom: 1px solid #e2e8f0;
	}

	.report-item:last-child {
		border-bottom: none;
	}

	.report-label {
		font-size: 28rpx;
		color: #475569;
	}

	.report-value {
		font-size: 30rpx;
		font-weight: 600;
		color: #0f172a;
	}

	.timeout-orders {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
		padding: 20rpx;
	}

	.order-card {
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		padding: 24rpx;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.card-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #1e40af;
	}

	.card-status {
		font-size: 26rpx;
		background-color: #e0f2fe;
		color: #0369a1;
		padding: 6rpx 14rpx;
		border-radius: 20rpx;
	}

	.card-content {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.card-row {
		font-size: 28rpx;
		color: #334155;
	}

	.card-label {
		color: #64748b;
		font-weight: bold;
	}

	.urgency-badge {
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
		font-size: 26rpx;
		font-weight: bold;
	}

	.urgency-high {
		background-color: #fee2e2;
		color: #b91c1c;
	}

	.urgency-medium {
		background-color: #fef3c7;
		color: #92400e;
	}

	.urgency-low {
		background-color: #d1fae5;
		color: #065f46;
	}


	.value {
		font-size: 28rpx;
		color: #333;
	}
</style>